#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "util.h"

#define SERVER_PORT    9090
#define MAX_BUFF_SIZE 1024

int main(int argc, char *argv[])
{
    struct sockaddr_in servaddr;
    char sendbuff[MAX_BUFF_SIZE];
    char recvbuff[MAX_BUFF_SIZE];
    int connfd;
    int ret = 0;

    if (argc < 2)
    {
        printf("usage: %s <server_ip>\n", argv[0]);
        return 1;
    }

    if (signal_intr(SIGPIPE, SIG_IGN) == SIG_ERR)
    {
        err_exit("set signal handler on SIGPIPE failed");
    }

    if ((connfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        err_exit("socket failed");
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERVER_PORT);
    if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) != 1)
    {
        err_exit("inet_pton failed, invaild IPv4 address");
    }

    if (connect(connfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        err_exit("connect failed");
    }

    while (fgets(sendbuff, MAX_BUFF_SIZE, stdin) != NULL)
    {
        if (put_string(connfd, sendbuff, sizeof(sendbuff) - 1) < 0)
        {
            err_exit("put_string failed");
        }

        memset(recvbuff, 0, sizeof(recvbuff));
        if ((ret = get_string(connfd, recvbuff, sizeof(recvbuff) - 1)) < 0)
        {
            err_exit("get_string failed");
        }
        else if (0 == ret)
        {
            break;
        }
        printf("%s", recvbuff);
    }

    return 0;
}
